package org.zyj.io.idle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.zyj.io.protocal.Message;

public class IdleInitializer extends ChannelInitializer<NioSocketChannel> {

    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        ch.pipeline() //配置pipeline
                .addLast(new IdleStateHandler(2, 3, 5))
                .addLast(new HeatBeatHandler())
                .addLast(new ReplayingMessageDecoder())
                .addLast(new ServerHandler())
        ;
    }


    static class ServerHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            Message m = (Message) msg;
            System.out.println(m);
            System.out.println(new String(m.getBody())); //暂时不管字符串编码的问题
        }
    }


    static class HeatBeatHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent event) {
                //这里可以做心跳检测, 如果长时间没有读写, 就可以做一些操作, 比如释放连接...
                System.out.println(event.state());
            }
        }
    }
}
